const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const rateLimit = require('express-rate-limit');

const app = express();

// 启用CORS
app.use(cors());

// 添加请求限制
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1分钟
  max: 10, // 限制每个IP 1分钟内最多10个请求
  message: '请求过于频繁，请稍后再试'
});

// 健康检查端点不需要限制
app.get('/health', (req, res) => {
  res.status(200).send('OK');
});

// 其他路由使用限制
app.use(limiter);

// 配置代理
const proxyOptions = {
  target: 'https://sns-video-hw.xhscdn.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api/video': '', // 移除 /api/video 前缀
  },
  onProxyReq: (proxyReq, req, res) => {
    // 添加必要的请求头
    proxyReq.setHeader('Accept', '*/*');
    proxyReq.setHeader('Accept-Encoding', 'identity;q=1, *;q=0');
    proxyReq.setHeader('Accept-Language', 'zh-CN,zh;q=0.9,en;q=0.8');
    proxyReq.setHeader('Connection', 'keep-alive');
    proxyReq.setHeader('Host', 'sns-video-hw.xhscdn.com');
    proxyReq.setHeader('Origin', 'https://www.xiaohongshu.com');
    proxyReq.setHeader('Range', 'bytes=0-');
    proxyReq.setHeader('Referer', 'https://www.xiaohongshu.com/');
    proxyReq.setHeader('Sec-Fetch-Dest', 'video');
    proxyReq.setHeader('Sec-Fetch-Mode', 'cors');
    proxyReq.setHeader('Sec-Fetch-Site', 'cross-site');
    proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36');
    proxyReq.setHeader('sec-ch-ua', '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"');
    proxyReq.setHeader('sec-ch-ua-mobile', '?0');
    proxyReq.setHeader('sec-ch-ua-platform', '"Windows"');
  },
  onProxyRes: (proxyRes, req, res) => {
    // 添加CORS头
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
    proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS';
    proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, Range';
  },
  onError: (err, req, res) => {
    console.error('代理错误:', err);
    res.status(500).send('代理服务器错误');
  },
  logLevel: 'debug'
};

// 使用代理中间件
app.use('/api/video', createProxyMiddleware(proxyOptions));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`代理服务器运行在端口 ${PORT}`);
  console.log('代理配置:', proxyOptions);
}); 